<template>
	<view class="container">
    <view class="list">
      <view class="multi-item">
        <view class="multi-item-child">
          <view class="title">收件人</view>
           <view class="content">
             <input class="uni-input text"  placeholder="请填写收件人"   v-model="real_name" />
           </view>
        </view>
        <view class="multi-item-child">
           <view class="title">联系方式</view>
           <view class="content">
             <input type='number' class="uni-input text" placeholder="填输入电话"  v-model="phone"  pattern="\d*" />
           </view>
        </view>
        <view class="multi-item-child">
           <view class="title">收件地区</view>
           <view class="content">
             <picker mode="multiSelector" @change="bindRegionChange"
             	@columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="multiArray">
             	<view class='acea-row'>
             		<view class="picker">{{region[0]}}，{{region[1]}}，{{region[2]}}</view>
             		<!-- <view class='iconfont icon-dizhi fontcolor'></view> -->
             	</view>
             </picker>
           </view>
        </view>
        <view class="multi-item-child">
           <view class="title">详细地址</view>
           <view class="content">
              <input type="textarea" class="uni-input text"  placeholder="填输入详细地址" v-model="detailAddress"  />
             <!-- <textarea  class="uni-input text" placeholder="填输入详细地址"  v-model="detailAddress" /> -->
           </view>
        </view>
        <view class="set-default-address-box">
          设置默认地址
          <switch  :checked="checked" color="#008DFF" style="transform:scale(0.6)" @change="switchChange"  />
        </view>
      </view>
    </view>
    
    <view class="multi-operate-box"  v-if="addressId">
      <view class="left" @tap="handleDelete">删除</view>
      <view class="right" @tap="onSumbmit">保存</view>
    </view>
    <view class="operate-box" @tap="onSumbmit"  v-else>保存</view>
	</view>
</template>

<script>
  import {
  	getCity
  } from '@/api/api.js';
  import {
  	editAddress,
  	getAddressDetail,
    delAddress,
    setAddressDefault
  } from '@/api/user.js';
  
	export default {
      data() {
        return {
          real_name: "",
          phone: "",
          multiIndex: [0, 0, 0],
          valueRegion: [0, 0, 0],
          multiArray: [],
          district: [],
          cityId: 0,
          region: [this.$t(`省`), this.$t(`市`), this.$t(`区`)],
          detailAddress: '',
          delivered_info_obj: {},
          checked: false,
          addressId: 0, //地址id
        }
      },
      computed: {
        
      },
      onLoad(options) {
        console.log('options', options)
        if(options.delivered_info){
           uni.setNavigationBarTitle({
             title: '编辑收件信息'
           })
           this.delivered_info_obj =  JSON.parse(decodeURIComponent(options.delivered_info))
           console.log('this.delivered_info_obj', this.delivered_info_obj)
           let {id, real_name, phone, is_default, province, city,  district, city_id,  detail} = this.delivered_info_obj
           this.addressId = id.toString()
           this.real_name = real_name
           this.phone = phone
           this.checked = (is_default == 1) ? true :  false
           this.region[0] = province
          this.region[1] = city
          this.region[2] = district
          this.cityId = city_id
          this.detailAddress = detail
        }else{
             uni.setNavigationBarTitle({
               title: '新增收件信息'
             })
        }
      	this.getCityList();
      },
      methods: {
              switchChange: function (e) {
                  console.log('switch1 发生 change 事件，携带值为', e.detail.value)
                  console.log('this.checked1', this.checked)
                  this.checked = e.detail.value
                  console.log('this.checked2', this.checked)
                  // this.setDefaultAddress(e)
              },
              /**
               * 设置默认地址
               */
              setDefaultAddress: function(e) {
              	let that = this;
              	setAddressDefault(that.addressId).then(res => {
              		that.$util.Tips({
              			title: that.$t(`设置成功`),
              			icon: 'success'
              		}, function() {
              			// that.$set(that, 'addressList', that.addressList);
              		});
              	}).catch(err => {
              		return that.$util.Tips({
              			title: err
              		});
              	});
              },
              getCityList: function() {
                let that = this;
                getCity().then(res => {
                  this.district = res.data
                 that.initialize();
                })
              },
              initialize() {
                 let that = this,
                   province = [],
                   city = [],
                   area = [];
                 let cityChildren = that.district[0].c || [];
                 let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
                 that.district.forEach((item, i) => {
                   province.push(item.n);
                   if (item.n === this.region[0]) {
                     this.valueRegion[0] = i
                     this.multiIndex[0] = i
                   }
                 });
                 that.district[this.valueRegion[0]].c.forEach((item, i) => {
                   if (this.region[1] == item.c) {
                     this.valueRegion[1] = i
                     this.multiIndex[1] = i
                   }
                   city.push(item.n);
                 });
                 that.district[this.valueRegion[0]].c[this.valueRegion[1]].c.forEach((item, i) => {
                   if (this.region[2] == item.c) {
                     this.valueRegion[2] = i
                     this.multiIndex[2] = i
                   }
                   area.push(item.n);
                 });
                 this.multiArray = [province, city, area]
              },
              bindRegionChange: function(e) {
                let multiIndex = this.multiIndex,
                  province = this.district[multiIndex[0]] || {
                    c: []
                  },
                  city = province.c[multiIndex[1]] || {
                    v: 0
                  },
                  multiArray = this.multiArray,
                  value = e.detail.value;
              
                this.region = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]]
                // this.$set(this.region,0,multiArray[0][value[0]]);
                // this.$set(this.region,1,multiArray[1][value[1]]);
                // this.$set(this.region,2,multiArray[2][value[2]]);
                this.cityId = city.v
                this.valueRegion = [0, 0, 0]
                this.initialize();
              },
              bindMultiPickerColumnChange: function(e) {
                let that = this,
                  column = e.detail.column,
                  value = e.detail.value,
                  currentCity = this.district[value] || {
                    c: []
                  },
                  multiArray = that.multiArray,
                  multiIndex = that.multiIndex;
                multiIndex[column] = value;
                switch (column) {
                  case 0:
                    let areaList = currentCity.c[0] || {
                      c: []
                    };
                    multiArray[1] = currentCity.c.map((item) => {
                      return item.n;
                    });
                    multiArray[2] = areaList.c.map((item) => {
                      return item.n;
                    });
                    break;
                  case 1:
                    let cityList = that.district[multiIndex[0]].c[multiIndex[1]].c || [];
                    multiArray[2] = cityList.map((item) => {
                      return item.n;
                    });
                    break;
                  case 2:
              
                    break;
                }
                // #ifdef MP || APP-PLUS
                this.$set(this.multiArray, 0, multiArray[0]);
                this.$set(this.multiArray, 1, multiArray[1]);
                this.$set(this.multiArray, 2, multiArray[2]);
                // #endif
                // #ifdef H5 
                this.multiArray = multiArray;
                // #endif
              
              
              
                this.multiIndex = multiIndex
                // this.setData({ multiArray: multiArray, multiIndex: multiIndex});
              }, 
              onSumbmit(){
                  let {real_name, phone, region, detailAddress, addressId, cityId} = this
                  console.log('real_name', real_name)
                  if(!real_name){
                    uni.showToast({
                      icon: 'none',
                      title: '请填写收件人'
                    })
                    return;
                  }
                  if(!phone){
                    uni.showToast({
                      icon: 'none',
                      title: '请输入电话'
                    })
                    return;
                  }
                  if(region[0] == this.$t(`省`)){
                    uni.showToast({
                      icon: 'none',
                      title: '请选择收件地区'
                    })
                    return;
                  }
                  if(!detailAddress){
                    uni.showToast({
                      icon: 'none',
                      title: '请输入详细地址'
                    })
                    return;
                  }
                  
                  let params = {
                    real_name,
                    phone,
                    detail: detailAddress
                  }
                  params.id = addressId
                    
                  params.address = {
                  	province: region[0],
                  	city: region[1],
                  	district: region[2],
                  	city_id: cityId,
                  };
                  
                  console.log('this.checked', this.checked)
                  params.is_default = this.checked ? 1 : 0;
                  
                  console.log('params---', params)
                  // return;
                  
                  let tips = '添加成功'
                  if(addressId){
                      tips = '编辑成功'
                  }else{
                     tips = '添加成功'
                  }  
                  editAddress(params).then(res => {
                    console.log('res', res)
                    this.handleSubmitSuccess(res.status, tips)
                  }).catch((err)=>{
                      uni.showToast({ title:err, icon:'none' })
                  })
              },
              handleSubmitSuccess(status, tips = '添加成功'){
                if(status == 200){
                  uni.showToast({
                    icon: 'none',
                    title: tips,
                    success() {
                    	uni.navigateBack()
                    }
                  })
                }else{
                   uni.showToast({ title:res.msg, icon:'none' })
                }
              },
              handleDelete(){
                 let that = this
                 uni.showModal({
                     title: '删除',
                     content: '确认删除吗？',
                     success: function (res) {
                         if (res.confirm) {
                             console.log('用户点击确定');
                             let {addressId} = that
                             if(addressId){
                                delAddress(addressId).then(res => {
                                  console.log('res', res)
                                  that.handleSubmitSuccess(res.status, '删除成功')
                                }).catch((err)=>{
                                    uni.showToast({ title:err, icon:'none' })
                                })
                             }
                         } else if (res.cancel) {
                             console.log('用户点击取消');
                         }
                     }
                 });
              }
      }
	}
</script>

<style lang="scss" scoped>
	page {
    min-height: 100vh;
		background-color: rgb(248,249,252);
	}

	.container {
		padding: 32rpx;
	}
  .list{
    
  }
  .item{
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #FFF;
    font-size: 28rpx;
    color: rgba(0,0,0,0.9);
    padding: 32rpx 28rpx;
    border-radius: 10rpx;
    margin-bottom: 24rpx;
  }
  .multi-item{
    width: 686rpx;
    padding: 32rpx 28rpx;
    margin-bottom: 24rpx;
    box-sizing: border-box;
    background: #FFFFFF;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    .multi-item-child{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24rpx 0;
      .title{
        width: 150rpx;
      }
      .content{
        display: flex;
        align-items: center;
        text-align: right;
        .text{
          margin-right: 10rpx;
          font-size: 28rpx;
          color: #333;
          text-align: right;
        }
        .picker-inner{
          display: flex;
          align-items: center;
        }
      }
    }
  }
  .set-default-address-box{
    padding: 24rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #FFF;
  }
  .operate-box{
    width: 686rpx;
    height: 96rpx;
    line-height: 96rpx;
    margin: 200rpx auto 30rpx;
    box-sizing: border-box;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    font-weight: 600;
    font-size: 32rpx;
    color: #FFFFFF;
    background: #008DFF;
    text-align: center;
    border-radius: 12rpx;
  }
  .multi-operate-box{
    display: flex;
    margin: 200rpx auto 30rpx;
    .left{
      width: 327rpx;
      height: 80rpx;
      border: 1rpx solid #008DFF;
      box-sizing: border-box;
      line-height: 80rpx;
      margin-right: 30rpx;
      text-align: center;
      background: #F2F3FF;
      border-radius: 12rpx 12rpx 12rpx 12rpx;
      font-weight: 600;
      font-size: 32rpx;
      color: #008DFF;
    }
    .right{
      width: 327rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #008DFF;
      border-radius: 12rpx 12rpx 12rpx 12rpx;
      font-weight: 600;
      font-size: 32rpx;
      color: #FFFFFF;
    }
  }
</style>
